package com.prig.base.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import com.prig.base.util.response.Result;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class PageController {
    @RequestMapping(value = "/")
    public String homePage() {
        return "templates/login.html";
    }
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response){
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator());
        // 重新生成code
        captcha.createCode();
        SecurityUtils.getSubject().getSession().setAttribute("captcha",captcha);
        try(ServletOutputStream os = response.getOutputStream()){
            captcha.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/getCaptchaStatus")
    @ResponseBody
    public Result getCaptchaStatus(){
        Object captchaStatus = SecurityUtils.getSubject().getSession().getAttribute("captchaStatus");
        if (captchaStatus == null)
            return new Result<>(false);
        else
            return new Result<>(Boolean.parseBoolean(captchaStatus.toString()));
    }
}
